<template>
  <div v-loading="loading" element-loading-text="加载中" element-loading-spinner="el-icon-loading">
    <el-table ref="tableRef" :stripe="true" :border="true" style="width: 100%" :class="tableCalss" :height="height"
      :max-height="maxHeight" :data="tableData" :row-key="rowKey" :empty-text="emptyText"
      @selection-change="handleSelectionChange" @select="handleSelect">
      <el-table-column v-if="enableSelection" fixed="left" width="40" align="center" type="selection"
        :reserve-selection="reserveSelection">
      </el-table-column>
      <el-table-column v-if="enableIndex" fixed="left" width="40" align="center" label="#" type="index"
        :index="handleIndexMethod">
      </el-table-column>
      <slot></slot>
    </el-table>
    <!--  分页  -->
    <div style="text-align: center; overflow-x: auto;">
      <el-pagination ref="paginationRef" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-sizes="pageSizes" :page-size="pageSize" :pager-count="pagerCount"
        :total="total" :prev-text="prevText" :next-text="nextText" :disabled="disabled"
        :hide-on-single-page="hideOnSinglePage" :layout="layout" background>
        <slot name='pt'>
          <span v-if="tableData.length === 0" class="el-pagination__total">没有匹配数据</span>
          <span v-else="" class="el-pagination__total">显示第 {{startIndex+1}} 至
            {{endIndex}}&nbsp;&nbsp;&nbsp;&nbsp;共{{total}}条</span>
        </slot>
      </el-pagination>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      dataSource: Array, //静态表格时数据
      loadingData: Function, //服务器模式-加载数据方法
      select: Function, //当用户手动勾选数据行的 Checkbox 时触发的事件	selection, row
      selectionChange: Function, //当选择项发生变化时会触发该事件	selection
      rowKey: { //数据对应的key标识
        type: String,
        default: 'id',
      },
      pageSize: { //每页条数
        type: Number,
        default: 10,
      },
      enableSelection: { //是否打开多选框
        type: Boolean,
        default: false,
      },
      reserveSelection: { //数据更新之后保留之前选中的数据（需指定 row-key）
        type: Boolean,
        default: true,
      },
      enableIndex: { //是否开启序号
        type: Boolean,
        default: true,
      },
      enableLoading: { //是否开启加载loading
        type: Boolean,
        default: true,
      },

      // 样式》》》
      tableCalss: String,
      height: Number,
      maxHeight: Number,
    },
    data() {
      return {
        name: '分页的table组件',
        tableData: [],
        multipleSelectionData: [], //多选

        currentPage: 1, //当前页
        pageSizes: [10, 20, 30, 50], //每页显示个数选择器的选项设置
        // pageSize: 10, //每页显示条目个数
        total: 0, //总条数
        pagerCount: 5, //页码按钮的数量，当总页数超过该值时会折叠(大于等于 5 且小于等于 21 的奇数)
        prevText: "上一页",
        nextText: "下一页",
        disabled: false, //是否禁用
        layout: "slot, prev, pager, next", //sizes, prev, pager, next, jumper, ->, total, slot
        hideOnSinglePage: false, //只有一页时是否隐藏分页

        emptyText: '暂无数据', //空数据时显示的文本内容
        successMessage: '暂无数据', //请求成功时，提示信息！
        errorMessage: '获取数据失败!!!', //请求失败时，提示信息！

        defaultAlign: "center", //默认表格对齐方式:left/center/right
        defaultHeaderAlign: "center",

        loading: true, //加载loading
      }
    },
    created() {},
    computed: {
      startIndex() {
        return this.tableData.length > 0 ? (this.currentPage - 1) * this.pageSize : 0;
      },
      endIndex() {
        return this.startIndex + this.tableData.length;
      },
    },
    mounted() {
      this.handleCurrentChange(this.currentPage);
    },
    methods: {
      handleSelect(val, row) {
        if (this.select) this.select(val, row);
      },
      handleSelectionChange(val) {
        this.multipleSelectionData = val;
        if (this.selectionChange) this.selectionChange(val);
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.draw()
      },
      handleCurrentChange(val) {
        this.showLoading();
        this.currentPage = val;
        if (this.loadingData) {
          // 加载动态表格数据
          this.handleTableData(this.hideLoading);
        } else {
          // 加载静态表格数据
          this.handleStaticTableDate();
          this.hideLoading();
        }
      },
      handleTableData(callback) {
        var params = {
          sEcho: this.currentPage,
          currentPage: this.currentPage,
          length: this.pageSize,
          start: (this.currentPage - 1) * this.pageSize,
        };
        var $this = this;
        this.loadingData(params, function(res) {
          if (res.status == '0' || res.status == '200') {
            var data = res.data;
            var tableData = data['data'] || data['aaData'] || [];
            var total = data['total'] || data['iTotalRecords'] || data['iTotalDisplayRecords'] || 0;
            $this.emptyText = $this.successMessage;
            $this.tableData = tableData;
            if (total > 0) $this.total = total;
            callback();
          } else {
            $this.emptyText = $this.errorMessage;
            $this.tableData = [];
            callback();
          }
        });
      },
      handleStaticTableDate() {
        var start = (this.currentPage - 1) * this.pageSize;
        var end = this.currentPage * this.pageSize;
        this.tableData = this.dataSource.slice(start, end);
        this.total = this.dataSource.length;
      },
      handleIndexMethod(index) {
        return this.startIndex + index + 1;
      },
      showLoading() {
        this.loading = this.enableLoading && true;
      },
      hideLoading() {
        this.loading = false;
      },
      toSelectedRows() {
        console.log('toSelectedRows', this.multipleSelectionData);
        // var keys = [];
        // this.multipleSelectionData.forEach(x => {
        //   keys.push(x[this.rowKey])
        // });
        // this.$nextTick(() => {
        //   var rows = this.tableData.filter(x => {
        //     return keys.indexOf(x[this.rowKey]) != -1;
        //   });
        //   console.log('toSelectedRows >>> rows', rows);
        //   rows.forEach(row => {
        //     this.$refs.tableRef.toggleRowSelection(row,true);
        //   });
        // })
        this.$nextTick(() => {
          this.multipleSelectionData.forEach(row => {
            this.$refs.tableRef.toggleRowSelection(row,true);
          });
        });
      },
      setMultipleSelectionData(rows) {
        this.multipleSelectionData = rows;
      },

      //******************************************
      //****************外部调用方法************
      /**
       * 重新渲染table的当前页
       */
      draw() {
        this.handleCurrentChange(this.currentPage);
      },
      /**
       * 刷新table，回到首页
       */
      refresh() {
        this.handleCurrentChange(1);
      },
      /**
       * 获取多选框选中数据
       */
      getSelectedData() {
        return this.multipleSelectionData;
      },
      /**
       * 获取当前页数据
       */
      getCurrentPageData() {
        return this.tableData;
      },
      /**
       * 获取table组件对象
       */
      getTable() {
        return this.$refs.tableRef;
      },
      /**
       * 获取分页组件对象
       */
      getPagination() {
        return this.$refs.paginationRef;
      },
    },
    watch: {
      'currentPage'() {
        // 是否清空多选框数据
        if (this.enableSelection && !this.reserveSelection) {
          this.multipleSelectionData = [];
        }
      },
      'dataSource'() {
        this.handleCurrentChange(1);
      },
      'tableData'() {
        console.log("tableData >>>")
        this.$nextTick(() => {
          this.toSelectedRows();
        });
      }
    }
  }
</script>

<style>
  body {
    margin: 0;
  }

  th {
    color: #606266;
  }

  button.btn-prev,
  button.btn-next {
    font-size: 13px;
    width: 70px;
  }

  button.btn-prev>span:hover {
    color: #409EFF;
  }

  button.btn-next>span:hover {
    color: #409EFF;
  }
</style>
